package com.power.model;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;

import java.util.Collection;
import java.util.HashSet;
import java.util.Set;

/**
 * security 容器能够认识的对象 (这整个项目的对象)
 */
@Data
@AllArgsConstructor
@NoArgsConstructor
public class SecurityUser implements UserDetails {

    /**
     * 商城后台管理系统登录对象
     */

    private Long userId;
    private String username;
    private String password;
    private Integer status;
    private String loginType;
    private Long shopId;
    private Set<String> perms = new HashSet<>();


    @Override // 在Security容器中生成唯一的id
    public String getUsername() {
        return this.loginType + this.userId;
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        return null;
    }

    @Override
    public boolean isAccountNonExpired() {
        return this.status == 1;
    }

    @Override
    public boolean isAccountNonLocked() {
        return this.status == 1;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return this.status == 1;
    }

    @Override
    public boolean isEnabled() {
        return this.status == 1;
    }


    public void setPerms(Set<String> perms) {
        //最终处理完成的权限的集合
        HashSet<String> finalPermsSet = new HashSet<>();
        perms.forEach(perm -> {
            if (perm.contains(",")) {
                String[] realPerms = perm.split(",");
                for (int i = 0; i < realPerms.length; i++) {
                    finalPermsSet.add(realPerms[i]);
                }

            }else {
                finalPermsSet.add(perm);
            }
        });
        this.perms = finalPermsSet;
    }
}
